<?php
namespace app\api\controller;

use app\api\controller\Authbase;
use app\api\model\ButtonModel;
use app\common\model\project_model\BasicConfigModel;
use think\Controller;

/**
 * 按钮相关系列接口
 */
class Button extends Authbase
{
    /**
     * 获取一组按钮
     */
    public function index() {
        $post = $this->request->post();
        $group_name = isset($post['group_name'])?$post['group_name']:null;
        $field = isset($post['filed'])?$post['field']:null;
        $key = isset($post['key'])?$post['key']:null;
        $type = isset($post['type'])?$post['type']:null;
        $buttonM = new ButtonModel();

        if ($field && !is_array($field)) {
            return json(['code' => 0, 'error' => 'field 必须是json格式']);
        } else if (is_array($field)) {
            $field = array_values($field);
        }
        if($group_name){
            $list = $buttonM::getButtonByGroup($group_name, $field);
        } else {
            if ($key && !is_array($key)) {
                return json(['code' => 0, 'error' => 'key 必须是json格式，获取单个按钮请走view接口']);
            } elseif(is_array($key)){
                $key = array_values($key);
            }

            $list = $buttonM::getButton($field, $type, $key);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => $list]);
    }

    /**
     * 获取一个按钮
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function view() {
        $key = input('key', '');
        $field = $this->request->post();
        $field = isset($field['field'])?$field['field']:null;
        if (empty($key)) {
            return json(['code' => 0, 'error' => '请传递参数key']);
        }
        if ($field && !is_array($field)) {
            return json(['code' => 0, 'error' => 'field 必须是json格式']);
        } elseif($field && is_array($field)) {
            $field = array_values($field);
        }
        $button =ButtonModel::getOneByKey($key, $field);
        return json(['code' => 1, 'msg' => 'success', 'data' => $button]);
    }

}